package com.jinzhi.jinzhidata.service.impl;

import com.jinzhi.jinzhidata.dataobject.User;
import com.jinzhi.jinzhidata.repository.UserRepository;
import com.jinzhi.jinzhidata.service.UserService;
import com.jinzhi.jinzhidata.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Map;


/**
 * @author vansl
 * @description
 * @date 2019-12-28 11:55
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public User userLogin(Map<String, String> userInfo) {
        String openid = userInfo.get("openid");
        String userWechatName = userInfo.get("nickname");
        String userAvatar = userInfo.get("headimgurl");
        String userGender = userInfo.get("sex");
        String userAddress = userInfo.get("country") + " " + userInfo.get("province") + " " + userInfo.get("city");
        User user = selectUserByUserWeChatId(openid);
        // 如果是第一次登录则新建用户
        if (user == null) {
            user = new User();
            String uuid = UUIDUtil.getUUID();
            user.setUserId(uuid);
            user.setUserWechatId(openid);
            user.setUserRole("user");
            user.setUserBalance(new BigDecimal(0));
        }
        // 否则更新用户信息
        user.setUserWechatName(userWechatName);
        // 如果自定义用户名为空，则把微信名称设置为自定义用户名
        if (StringUtils.isEmpty(user.getUserName())) {
            user.setUserName(userWechatName);
        }
        user.setUserAvatar(userAvatar);
        user.setUserGender(userGender);
        user.setUserAddress(userAddress);
        userRepository.save(user);
        return user;
    }

    @Override
    public User selectUserByUserWeChatId(String openid) {
        User user = new User();
        user.setUserWechatId(openid);
        Example<User> example = Example.of(user);
        return userRepository.findOne(example).orElse(null);
    }

    @Override
    public User selectUserByUserId(String userId) {
        return userRepository.findById(userId).orElse(null);
    }

    @Override
    @Transactional
    public Integer updateUserBalance(String userId, BigDecimal changedBalance) {
        return userRepository.updateUserBalance(userId, changedBalance);
    }

    @Override
    public User updateUserInfo(User user) {
        return userRepository.save(user);
    }

    @Override
    public User selectUserByUserPhone(String userPhone) {
        User user = new User();
        user.setUserPhone(userPhone);
        Example<User> example = Example.of(user);
        return userRepository.findOne(example).orElse(null);
    }
}
